/*  GStruct: data structure helpers for Java
 *  Copyright (C) 2011 Giulio Franco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package gstruct.sequential;

import java.util.AbstractCollection;
import java.util.Collections;
import java.util.Iterator;

/**
 * Promotes an iterable to a readonly collection, by calculating its size.
 * <p><b>Beware</b> that this class will fail if the base iterable
 * is modified after the creation of this collection</p>
 * The size is only computed upon construction,
 * in contrast to {@link DynamicallySizedIterable}, which computes it
 * every time {@link DynamicallySizedIterable#size() size()} is called.
 * @author Giulio Franco <giulio_franco@msn.com>
 *
 * @param <E> Type of the contained objects
 */
public class StaticallySizedIterable<E> extends AbstractCollection<E> {
	
	private final Iterable<E> baseIterable;
	private final int size;
	
	public StaticallySizedIterable() {
		baseIterable = Collections.emptyList();
		size = 0;
	}
	
	public StaticallySizedIterable(Iterable<E> base) {
		this.baseIterable = base;
		int mSize = 0;
		for (@SuppressWarnings("unused") E e : base) {
			mSize += 1;
		}
		size = mSize;
	}
	
	public StaticallySizedIterable(Iterable<E> base, int size) {
		this.baseIterable = base;
		this.size = size;
	}
	
	@Override
	public Iterator<E> iterator() {
		return baseIterable.iterator();
	}

	@Override
	public int size() {
		return size;
	}
	
}
